/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.openfeign.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.moon.framework.autoconfigure.MoonConstants;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * 创建Feign请求拦截器，在发送请求前标识此请求是来自feign调用，同时传递请求头参数
 * @author moon
 */
public class FeignRequestInterceptor implements RequestInterceptor {
	
	@Override
	public void apply(RequestTemplate template) {
	    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //请求头参数
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                template.header(name, values);
            }
        }
        //以下是携带请求参数，根据需要使用
        Enumeration<String> bodyNames = request.getParameterNames();
        if (bodyNames != null) {
            while (bodyNames.hasMoreElements()) {
                String name = bodyNames.nextElement();
                String values = request.getParameter(name);
                template.header(name, values);
            }
        }
        //固定标识
        template.header(MoonConstants.REQUEST_FROM, MoonConstants.RequestFormEnum.feign.name());
	}
}
